package edu.scause.gs.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Transaction;

import edu.scause.gs.dao.AdminDAO;
import edu.scause.gs.dao.MsgDAO;
import edu.scause.gs.model.Msg;
import edu.scause.gs.model.Orders;

public class Tools {

	public long get_Date(String bought_date) throws ParseException {
		long count_day = 0;
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
		count_day = (new Date().getTime() - myFormat.parse(bought_date).getTime()) / 
				(24 * 60 * 60 * 1000);
		return count_day;
	}
	
	public double get_Variance(List<Double> score) {
		double sum = 0;
		double avg = 0;
		double variance = 0;
		//System.out.println(score.size());
		do {
			sum = 0;
			avg = variance = 0;
			Iterator<Double> it = score.iterator();
			while (it.hasNext()) {
				double d = (double) it.next();
				sum += d;
			}
			//System.out.println(score.size());
			avg = sum / score.size();
			for (int i = 0; i < score.size(); i++) {
				variance += (score.get(i) - avg) * (score.get(i) - avg);
				
			}
			//System.out.println(variance);
			//System.out.println(avg);
		} while (del_Error(avg, variance, score));
		
		return variance;
	}
	
	public boolean del_Error(double average, double varinance, List<Double> score) {
		boolean flag = false;
		for (int i = 0; i < score.size(); i++) {
			if (score.get(i) < (2 * (average - varinance)) &&
					score.get(i) > (2 * (average - varinance))) {
				score.remove(i);
				flag = true;
			}
		}
		return flag;
	}
	
	public boolean sendMSG(String adminid, Orders orders) {
		MsgDAO msgDAO = new MsgDAO();
		AdminDAO adminDAO = new AdminDAO();
		Msg msg = new Msg();
		msg.setAdmin(adminDAO.findById(Integer.parseInt(adminid)));
		msg.setClient(orders.getClient());
		msg.setAmount(orders.getAmount());
		msg.setGoodsname(orders.getGoodsInfo().getGoodsName());
		msg.setShoppingdate(orders.getShoppingDate());
		
		try {
			Transaction ts = msgDAO.getSession().beginTransaction();
			msgDAO.save(msg);
			ts.commit();
			msgDAO.getSession().close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}
	
}
